<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <script>
    
    // 反转链表
    function reverseLinkedList(head) {
      let prev = null;
      let curr = head;

      while (curr) {
        let next = curr.next; // 暂存下一个节点
        curr.next = prev;     // 当前节点指向“前一个”节点，反转指针
        prev = curr;          // 移动 prev 到当前节点
        curr = next;          // 继续处理下一个节点
      }

      return prev; // prev 最终会指向新的头节点
    }

    // 测试
    function ListNode(val) {
      this.val = val;
      this.next = null;
    }

    const head = new ListNode(1);
    head.next = new ListNode(2);
    head.next.next = new ListNode(3);
    head.next.next.next = new ListNode(4);
    head.next.next.next.next = new ListNode(5);


    console.log('head:', head);
    const reversedHead = reverseLinkedList(head);
    console.log('Reversed Linked List:', reversedHead);


  </script>
</body>
</html>